require([],function(){
    var menuInfo = {
        table: '#menuGrid',
        pager: '#menuGridPager',
        initGrid: function(){
            $(menuInfo.table).jqGrid({
                url:"/resource/list",
                colModel:[
                    {name:"id",index:"id",key:true,hidden:true},
                    {name:"menuName",index:"menuName",label:"菜单名称",width:20,sortable: false},
                    {name:"iconName",index:"iconName",label:"图标名称",width:20,sortable: false},
                    {name:"menuNo",index:"menuNo",label:"排序编码",width:20,sortable: false},
                    {name:"createTime",index:"createTime",label:"创建时间",width:20,sortable: false},
                    {name:"url",index:"url",label:"资源路径",width:40,sortable: false},
                    {name:"parentId",index:'parentId',label:"父级ID",hidden:true}
                ],
                treeGrid: true,
                datatype:'json',
                treeGridModel: 'adjacency',
                ExpandColumn: "menuName",
                search: true,
                autowidth: true,
                height: "100%",
                rownum: -1,
                sortname: "menuNo",
                sortorder: "asc",
                pager: menuInfo.pager,
                scrollrows:true,
                ExpandColClick:true,
                treeReader:{
                    "parent_id_field": "parentId",
                    "level_field":"level",  // 树的等级根节点为0，一次递增
                    "leaf_field":"isLeaf" // 是否是子节点
                }
            });
            $(menuInfo.table).jqGrid('filterToolbar');
            menuInfo.initButton();
        },
        initButton: function(){
            $("#sys_menu_add").click(function(){
                menuInfo.initDialog(true);
            });
            $("#sys_menu_role_config").click(function(){
                var id = $(menuInfo.table).jqGrid('getGridParam', 'selrow');
                if (!id) {
                    toastr.warning("请选择要修改的菜单");
                    return false;
                }
                var row = $(menuInfo.table).jqGrid('getRowData', id);
                var rAjax = $.get('/role/list');
                var rsAjax = $.get("/role/getRoleIdsByResourceId",{resourceId:id});
                $.when(rAjax,rsAjax).done(function(rData,roleData){
                    var roles = rData[0];
                    var roleIds = roleData[0];
                    BootstrapDialog.show({
                        title : '角色配置',
                        size : BootstrapDialog.SIZE_NORMAL,
                        backdrop : true,
                        message : $('<div></div>').load('/fashion/menu/role/config'),
                        onshown: function(dialog) {
                            $.each(roles,function(index,node){
                                var option = '<option value="{0}">{1}</option>'.format(node.id,node.roleName);
                                $("#menu_role_form [name='roleIds']").append(option);
                                $("#menu_role_form [name='roleIds']").selectpicker('refresh');
                                $("#menu_role_form [name='roleIds']").selectpicker('render');
                            });
                            var json = {
                                menuName: row.menuName,
                                roleIds: roleIds
                            }
                            $("#menu_role_form").initForm(json);
                        },
                        buttons : [{
                            id : 'button',
                            label : '确定',
                            cssClass : 'btn-primary',
                            action : function(dialog) {
                                dialog.close();
                            }
                        }, {
                            label : '取消',
                            action : function(dialog) {
                                dialog.close();
                            }
                        }]
                    });
                });
            });
            $("#sys_menu_edit").click(function(){
                var id = $(menuInfo.table).jqGrid('getGridParam', 'selrow');
                if (!id) {
                    toastr.warning("请选择要修改的菜单");
                    return false;
                }
                menuInfo.initData(id,function(node){
                    menuInfo.initDialog(true, node);
                });
            });
            $("#sys_menu_view").click(function(){
                var id = $(menuInfo.table).jqGrid('getGridParam', 'selrow');
                if (!id) {
                    toastr.warning("请选择要查看的菜单");
                    return false;
                }
                menuInfo.initData(id,function(node){
                    menuInfo.initDialog(false, node);
                });
            });
            $("#sys_menu_del").click(function(){
                menuInfo.delMenu();
            });
        },
        initData: function(id,callback){
            if(id){
                $.ajax({
                    url:'/resource/list/'+id,
                    async: false,
                    success: function(node){
                        callback(node);
                    }
                });
            }else{
                callback();
            }
        },
        initDialog:function(isEdit,data){
            var rAjax = $.get("/resource/list/excludeNode",{resourceId:data?data.id:""});
            BootstrapDialog.show({
                title : '菜单信息',
                size : BootstrapDialog.SIZE_NORMAL,
                backdrop : true,
                message : $('<div></div>').load('/fashion/menu/save'),
                onshown: function(dialog) {
                    $.when(rAjax).done(function(zNodes){
                        $("#menu_form").initForm(data);
                        debugger;
                        if (data) {
                            $("#menu_form").find('[name="menuNo"]').removeAttr("readonly");
						}
                        menuInfo.initComponent(zNodes);
                        if(!isEdit){
                            $("#menu_form").readonly();
                            dialog.getButton('button').disable();
                        }else{
                            menuInfo.validateMenu();
                        }
                    });
                },
                buttons : [
                    {
                        id : 'button',
                        label : '确定',
                        cssClass : 'btn-primary',
                        action : function(dialog) {
                            menuInfo.saveMenu(function(){
                                dialog.close();
                            });
                        }
                    },
                    {
                        label : '取消',
                        action : function(dialog) {
                            dialog.close();
                        }
                    }]
            });
        },
        saveMenu:function(callback){
            var bootstrapValidator = $('#menu_form').data('bootstrapValidator');
            bootstrapValidator.validate();
            if (bootstrapValidator.isValid()) {// 如果校验成功后执行的操作
                var json = $('#menu_form').serializeObject();
                $.ajax({
                    url : '/resource/save',
                    type : 'post',
                    async:false,
                    dataType : 'json',
                    data : json,
                    success : function(data) {
                        toastr.result(data,function(){
                            callback();
                            $(menuInfo.table).reloadTable();
                        });
                    }
                });
            }
        },
        delMenu: function(){
            // 获取选中行的id
            var id = $(menuInfo.table).jqGrid('getGridParam', 'selrow');
            if (!id) {
                toastr.warning("请选择要删除的菜单");
                return false;
            };
            $.confirm("确定要删除该菜单吗",function(){
                $.post("/resource/delete", {id : id}, function(data) {
                    toastr.result(data,function(){
                        $(menuInfo.table).reloadTable();
                    });
                });
            });
        },
        initComponent: function(zNodes){
            var defaults = {
                height: 200,
                zNodes: zNodes,
                chkStyle: "radio",
                name : "menuName",
                parentId : "parentId"
            };
            $('#menu_form [name="parentId"]').drawMultipleTree(defaults);
        },
        validateMenu: function(){
            $("#menu_form").bootstrapValidator({
                feedbackIcons : {// 根据验证结果显示的各种图标
                    valid : 'glyphicon glyphicon-ok',
                    invalid : 'glyphicon glyphicon-remove',
                    validating : 'glyphicon glyphicon-refresh'
                },
                fields : {
                    menuName : {
                        validators : {
                            notEmpty : {
                                message : '菜单名称不能为空'
                            }
                        }
                    },
                    iconName : {
                        validators : {
                            notEmpty : {
                                message : '菜单图标不能为空'
                            }
                        }
                    }
                }
            });
        }
    }
    menuInfo.initGrid();
});

